package com.meatball.dronefly.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.meatball.dronefly.utils.MWebSocketClient;

import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import cn.hutool.core.util.ObjectUtil;

/**
 * 服务类
 * @author 张翔宇
 * @since 2022年9月8日
 */
public class WebSocketClientService extends Service {
    private String TAG="WebSocketClientService";
    private URI uri;
    public MWebSocketClient client;
    private WebSocketClientBinder binder = new WebSocketClientBinder();

    /**
     * 用于Activity和service通讯
     */
    public class WebSocketClientBinder extends Binder {
        public WebSocketClientService getService() {
            return WebSocketClientService.this;
        }
    }
    public WebSocketClientService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化websocket
        initSocketClient();
        // 开启心跳检测
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);
    }

    /**
     * 初始化websocket连接
     */
    private void initSocketClient() {
        URI uri = URI.create("ws://192.168.3.21:8080/websocket/1");
        client = new MWebSocketClient(uri) {
            @Override
            public void onMessage(String message) {
                super.onMessage(message);
                Log.e("WebSocketClientService", "收到的消息：" + message);
                // 广播接收到的消息,在Activity接收
                Intent intent = new Intent();
                intent.setAction("com.meatball.dronefly.servicecallback.content");
                intent.putExtra("message", message);
                sendBroadcast(intent);
            }

            @Override
            public void onOpen(ServerHandshake handshakedata) {
                super.onOpen(handshakedata);
                Log.e("JWebSocketClientService", "websocket连接成功");
            }
        };
        connect();
    }

    /**
     * 连接websocket
     */
    private void connect() {
        new Thread(() -> {
            try {
                //connectBlocking多出一个等待操作，会先连接再发送，否则未连接发送会报错
                client.connectBlocking();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //    -------------------------------------websocket心跳检测------------------------------------------------
    private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒进行一次对长连接的心跳检测
    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            Log.e("JWebSocketClientService", "心跳包检测websocket连接状态");
            if (ObjectUtil.isNotNull(client)) {
                if (client.isClosed()) {
                    reconnectWs();
                } else {
                    // 业务逻辑 这里如果服务端需要心跳包为了防止断开 需要不断发送消息给服务端
                    // client.send("心跳。");
                }
            } else {
                client = null;
                initSocketClient();
            }
            // 每隔一定的时间，对长连接进行一次心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };

    /**
     * 开启重连
     */
    private void reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable);
        new Thread(() -> {
            Log.e("JWebSocketClientService", "开启重连");
            try {
                client.reconnectBlocking();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}